from pydantic import BaseModel, EmailStr, Field, field_validator
from typing import Optional
from datetime import datetime

class UserBase(BaseModel):
    """用户基础信息"""
    email: Optional[EmailStr] = None  # 允许为空（仅管理员）
    username: str = Field(..., min_length=3, max_length=50)

class UserCreate(UserBase):
    """用户注册模型"""
    password: str = Field(..., min_length=8, description="密码至少8位")

class UserInDB(UserBase):
    """数据库存储的用户模型"""
    hashed_password: str
    disabled: bool = False
    role: str = "user"  # 可选值: "user" 或 "admin"
    created_at: datetime = Field(default_factory=datetime.utcnow)
    updated_at: Optional[datetime] = None

class UserOut(BaseModel):
    """返回给客户端的用户信息（不包含密码）"""
    id: str
    username: str
    email: Optional[EmailStr] = None  # 允许为空（管理员可能没有邮箱）
    role: str
    disabled: bool
    created_at: datetime

    class Config:
        from_attributes = True

